/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Database;

import Models.Contract;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author trang_000
 */
public class ContractDAO {

    private Connection conn;

    public ContractDAO() {
        conn = DBFactory.createConnection("dormitoryv2");
    }

    public boolean insertContract(Contract contract, int profileID) {
        boolean result = false;
        PreparedStatement ps = null;
        try {
            String sql = "INSERT INTO contract(description,dateCreated,dateBegin, dateEnd, profileID) "
                    + "VALUES (?, ?, ?, ?, ?);";
            ps = conn.prepareStatement(sql);
            System.out.println(contract.getDescription());
            ps.setString(1, contract.getDescription());
            ps.setDate(2, new java.sql.Date(new Date().getTime()));
            ps.setDate(3, new java.sql.Date(contract.getDateBegin().getTime()));
            ps.setDate(4, new java.sql.Date(contract.getDateEnd().getTime()));

            ps.setInt(5, profileID);
            ps.executeUpdate();
            result = true;
        } catch (Exception ex) {
            //Logger.getLogger(AuthenticationDAO.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.toString());
        }
        System.out.println(result);
        return result;
    }

    public Contract getMyContract(int userID, int contractStatus, int profileStatus) {
        Contract result = new Contract();
        String sql = "SELECT * FROM contract "
                + "inner join profile "
                + "on contract.profileID = profile.profileID "
                + "where profile.status = ? and contract.status = ? "
                + "and profile.userID= ? ;";
        
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, profileStatus);
            ps.setInt(2, contractStatus);
            ps.setInt(3, userID);

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                
                result.setContractID(rs.getInt(1));
                result.setDateCreated(rs.getDate(4));
                result.setDateBegin(rs.getDate(5));
                result.setDateEnd(rs.getDate(6));                     
            }

        } catch (SQLException ex) {

        }
        return result;
    }
}
